﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace DAWSharp.Common.Helpers
{
    public class BWHelper<T>
    {
        private Func<T> workMethod;
        private Action<T> completeMethod;
        public static void StartBackgroundworker(Func<T> workMethod, Action<T> completeMethod)
        {
            BWHelper<T> bWrap = new BWHelper<T>();
            bWrap.workMethod = workMethod;
            bWrap.completeMethod = completeMethod;
            bWrap.Start();
        }

        private void Start()
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            completeMethod((T)e.Result);
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = workMethod();
        }
    }
}
